<?php
require_once dirname(__FILE__) . '/libraries/ServiceBase.php';
require_once SDK_OA_LIB . 'util/helper/PHPMailer.php';
/**
 * Authen Service
 *
 */
class SDOServiceAuthen extends ServiceBase
{
    # 正式环境添加应用接口
    const AUTHEN_APP_OP_URL = 'AUTHEN_APP_OP_URL';
    # 测试环境添加应用接口
    const PRE_AUTHEN_APP_OP_URL = 'PRE_AUTHEN_APP_OP_URL';
    # 正式环境查询应用接口
    const AUTHEN_APP_SEARCH_URL = 'AUTHEN_APP_SEARCH_URL';
    # 测试环境查询应用接口
    const PRE_AUTHEN_APP_SEARCH_URL = 'PRE_AUTHEN_APP_SEARCH_URL';
    # 正式环境信任IP接口
    const IP_AUTHEN_TRUST_OP_URL = 'IP_AUTHEN_TRUST_OP_URL';
    # 测试环境信任IP接口
    const PRE_AUTHEN_IP_TRUST_OP_URL = 'PRE_AUTHEN_IP_TRUST_OP_URL';
    # 玩家游戏内测属性修改接口
    const MODIFY_PERM_USER = "MODIFY_PERM_USER";
    const PRE_MODIFY_PERM_USER = "MODIFY_PERM_USER";
    # 玩家游戏内测属性查询接口
    const QUERY_PERM_USER = "QUERY_PERM_USER";
    const PRE_QUERY_PERM_USER = "QUERY_PERM_USER";
    const CAS_WSDL = "AUTHEN_CAS_WSDL";
    const PRE_CAS_WSDL = "PRE_AUTHEN_CAS_WSDL";
    # SSO接口
    const SSO_WSDL = "AUTHEN_SSO_WSDL";
    const PRE_SSO_WSDL = "PRE_AUTHEN_SSO_WSDL";
    const APP_TEST_STATUS = 1;
    const APP_ONLINE_STATUS = 2;
    const TRUST_IP_MAILER = 'TRUST_IP_MAILER';
    protected static $testStatus = array(
        self::APP_TEST_STATUS => 1, 
        self::APP_ONLINE_STATUS => 0
    );
    /**
     * 开通认证、添加应用
     *
     * @param array|string $message // array(code,msg)
     * @param int $appId
     * @param string $appName
     * @param int $test 应用状态 1测试 2正式
     * @param string $env
     * @return boolean
     */
    public static function addApp (&$message, $appId, $appName, $test = 1, $env = SDK_ENV_TEST)
    {
        $op = 'add';
        $url = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_AUTHEN_APP_OP_URL) : sdk_fetch_config(
        SDK_ENV . self::AUTHEN_APP_OP_URL);
        $url .= $op;
        $param['appId'] = $appId;
        $param['appName'] = iconv('utf-8', 'gb2312', $appName);
        $param['test'] = self::$testStatus[$test];
        $urlSuffix = strtr(http_build_query($param), array(
            "&amp;" => "&"
        ));
        $content = self::getRestfulContent($url . '&' . $urlSuffix, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $urlSuffix , SDK_LOG_ENV=>$env);
        if ($content === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $errMsg[SDK_LOG_REUTRN] = $content;
        if (! ($content === "0" || $content == - 610502 || $content == - 610302)) {
            $logLevel = $content && ($content == - 610352 || $content == - 610503) ? 'warn' : 'error';
            if($content) {
                self::setErrNo($content);
            }
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::$logLevel($errMsg, __CLASS__);
            $message = $content;
            return false;
        }
        $logSuccess = true;
        if ($content == - 610502 || $content == - 610302) {
        	$logSuccess = false;
        }
        self::log($errMsg, __CLASS__, $logSuccess);
        return true;
    }
    /**
     * 查询应用信息
     *
     * @param array|string $message // array(code,msg)
     * @param int $appId
     * @param string $env
     * @return array|boolean
     */
    public static function searchApp (&$message, $appId, $env = SDK_ENV_TEST)
    {
        $op = 'search';
        $url = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_AUTHEN_APP_SEARCH_URL) : sdk_fetch_config(
        SDK_ENV . self::AUTHEN_APP_SEARCH_URL);
        $url .= $op;
        $param['appId'] = $appId;
        $urlSuffix = strtr(http_build_query($param), array(
            "&amp;" => "&"
        ));
        $content = self::getRestfulContent($url . '&' . $urlSuffix, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $urlSuffix , SDK_LOG_ENV=>$env);
        if ($content === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $result = explode('^$^', $content);
        if ($result[0] != - 610601) {
            $errMsg[SDK_LOG_REUTRN] = $content;
            self::log($errMsg, __CLASS__);
            if(isset($result[0]) && $result[0]) {
                self::setErrNo($result[0]);
            }
            $message = isset($result[1]) ? $result[1] : '接口错误' . $result[0];
            return false;
        }
        return $result;
    }
    /**
     * 修改应用编码接口的test属性值
     * 
     * @param string $message 错误信息
     * @param int $appId 应用ID
     * @param int $test 应用状态 1测试 2正式
     * @param string $env 环境
     * 
     * @return boolean
     */
    public static function editAppStatus (&$message, $appId, $test = 2, $env = SDK_ENV_TEST)
    {
        $op = 'editTest';
        $url = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_AUTHEN_APP_SEARCH_URL) : sdk_fetch_config(
        SDK_ENV . self::AUTHEN_APP_SEARCH_URL);
        $url .= $op;
        $param['appId'] = $appId;
        $param['test'] = self::$testStatus[$test];
        //$param['test'] = $test;
        $urlSuffix = strtr(http_build_query($param), 
        array(
            "&amp;" => "&"
        ));
        $content = self::getRestfulContent($url . '&' . $urlSuffix, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $urlSuffix , SDK_LOG_ENV=>$env);
        if ($content === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $result = explode('^$^', $content);
        $errMsg[SDK_LOG_REUTRN] = $content;
        if ($result[0] != - 611101) {
            $errMsg[SDK_LOG_LOCATION] = $url;
            $logLevel = $result[0] && ($result[0] == - 611103 || $result[0] == - 611102) ? 'warn' : 'error';
            self::$logLevel($errMsg, __CLASS__);
            $message = isset($result[1]) ? $result[1] : '接口错误' . $result[0];
            if(isset($result[0]) && $result[0]) {
                self::setErrNo($result[0]);
            }
            return false;
        }
        self::log($errMsg, __CLASS__, true);
        return true;
    }
    /**
     * 添加信任IP
     *
     * @param array|string $message // array(code,msg)
     * @param string $ip
     * @param string $env
     * @return boolean
     */
    public static function addTrustIP (&$message, $ip, $appId, $areaId, $groupId, $env = SDK_ENV_TEST)
    {
        if (self::searchTrustIP($message, $ip, $env)) {
            self::mail($ip, $appId, $areaId, $groupId);
        	return true;
        }
        $message = '';
        $op = 'add';
        $url = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_AUTHEN_IP_TRUST_OP_URL) : sdk_fetch_config(
        SDK_ENV . self::IP_AUTHEN_TRUST_OP_URL);
        $url .= $op;
        $param['IP'] = $ip;
        $urlSuffix = strtr(http_build_query($param), array(
            "&amp;" => "&"
        ));
        $content = self::getRestfulContent($url . '&' . $urlSuffix, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $urlSuffix , SDK_LOG_ENV=>$env);
        if ($content === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $result = explode('^$^', $content);
        $errMsg[SDK_LOG_REUTRN] = $content;
        if ($result[0] != - 610701) {
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::warn($errMsg, __CLASS__);
            $message = isset($result[1]) ? $result[1] : '接口错误' . $result[0];
            if(isset($result[0]) && $result[0]) {
                self::setErrNo($result[0]);
            }
            return false;
        }
        self::log($errMsg, __CLASS__, true);
        self::mail($ip, $appId, $areaId, $groupId);
        return true;
    }
    /**
     * 查询信任IP
     *
     * @param array|string $message // array(code,msg)
     * @param string $ip
     * @param string $env
     * @return array|boolean
     */
    public static function searchTrustIP (&$message, $ip, $env = SDK_ENV_TEST)
    {
        $op = 'search';
        $url = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_AUTHEN_IP_TRUST_OP_URL) : sdk_fetch_config(
        SDK_ENV . self::IP_AUTHEN_TRUST_OP_URL);
        $url .= $op;
        $param['IP'] = $ip;
        $urlSuffix = strtr(http_build_query($param), array(
            "&amp;" => "&"
        ));
        $content = self::getRestfulContent($url . '&' . $urlSuffix, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $urlSuffix , SDK_LOG_ENV=>$env);
        if ($content === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $result = explode('^$^', $content);
        if ($result[0] != - 610801) {
            $errMsg[SDK_LOG_REUTRN] = $content;
            self::log($errMsg, __CLASS__);
            $message = isset($result[1]) ? $result[1] : '接口错误' . $result[0];
            if(isset($result[0]) && $result[0]) {
                self::setErrNo($result[0]);
            }
            return false;
        }
        return true;
        //return in_array($result[0], array(- 610801 , - 610802)) ? $result : FALSE;
    }
    /**
     * 玩家游戏内测属性查询接口
     * @param mixed $message
     * @param string $uuid 数字账号
     * @param int $appId 游戏ID
     * @param int $gamearea 游戏区号
     * @param string $env 环境
     * 
     * @return boolean
     */
    public static function QueryPermissionUserGame (&$message, $uuid, $appId, $gamearea = 999, $env = SDK_ENV_TEST)
    {
        $url = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_QUERY_PERM_USER) : sdk_fetch_config(
        SDK_ENV . self::QUERY_PERM_USER);
        $params = array(
            'uuid' => $uuid, 
            'appId' => $appId, 
            'appArea' => $gamearea
        );
        $urlSuffix = strtr(http_build_query($params), array(
            "&amp;" => "&"
        ));
        $content = self::getRestfulContent($url . '?' . $urlSuffix, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $urlSuffix , SDK_LOG_ENV=>$env);
        if ($content === FALSE) {
            //$message = array('-2' , $message); 
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::fatal($errMsg, __CLASS__);           
            return FALSE;
        }
        $errMsgCode = array(
            1 => "权限受限", 
            2 => "系统错误，失败", 
            3 => "拒绝查询", 
            4 => "用户不存在", 
            5 => "账号无内测权限", 
            6 => "账号输入为空"
        );
        if ($content !== "0") {
            if ($content) {
                $message = isset($errMsgCode[$content]) ? $errMsgCode[$content] : "UNDEFINED ERROR:\t{$content}";
                self::setErrNo($content);
            }
            return false;
        }
        return true;
    }
    /**
     * 批量查询权限接口
     * @param array $uuids
     * @param int $appId
     * @param int $gamearea
     * @param string $env
     * 
     * return array($uid1=>false, $uid2=>true, ,,,);
     */
    public static function queryPermissionMulti ($uuids, $appId, $gamearea = 999, $env = SDK_ENV_TEST)
    {
        $result = array();
        $message = '';
        foreach ($uuids as $uuid) {
            $result[$uuid] = self::QueryPermissionUserGame($message, $uuid, $appId, $gamearea, $env);
        }
        return $result;
    }
    /**
     * 玩家游戏内测属性批量修改接口
     * @param string $message
     * @param array $uuids
     * @param int $appId
     * @param int $gamearea 
     * @param int $permissionvalue 0 没有内测权限 1 有
     * @param string $env
     * 
     * return array(数字ID=>array(result=>true, message=>''), 数字ID2=>array(result=>true, message=>''),,)
     */
    public static function modifyPermissionMulti ($uuids, $appId, $gamearea = 999, $permissionvalue, $env = SDK_ENV_TEST)
    {
        $result = array();
        foreach ($uuids as $uuid) {
            $row = array();
            $row['result'] = self::ModifyPermissionUserGame($row['message'], $uuid, $appId, $gamearea, 
            $permissionvalue, $env);
            $result[$uuid] = $row;
        }
        return $result;
    }
    /**
     * 玩家游戏内测属性修改接口
     * @param mixed $message
     * @param string $uuid 数字账号
     * @param int $appId 游戏ID
     * @param int $gamearea 游戏区号
     * @param int $permissionvalue 0 没有内测权限 1 有
     * @param string $env 环境
     * 
     * @return boolean
     */
    public static function ModifyPermissionUserGame (&$message, $uuid, $appId, $gamearea = 999, $permissionvalue, $env = SDK_ENV_TEST)
    {
        $url = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_MODIFY_PERM_USER) : sdk_fetch_config(
        SDK_ENV . self::MODIFY_PERM_USER);
        $params = array(
            'uuid' => $uuid, 
            'appId' => $appId, 
            'appArea' => $gamearea, 
            'permissionvalue' => $permissionvalue
        );
        $urlSuffix = strtr(http_build_query($params), array(
            "&amp;" => "&"
        ));
        $content = self::getRestfulContent($url . '?' . $urlSuffix, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $urlSuffix , SDK_LOG_ENV=>$env);
        $errMsgCode = array(
            1 => "权限受限", 
            2 => "系统错误，失败", 
            3 => "拒绝查询", 
            4 => "用户不存在", 
            5 => "账号输入为空", 
            6 => "内测属性值为空或不合法"
        );
        if ($content === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::fatal($errMsg, __CLASS__); 
            return FALSE;
        }
        $errMsg[SDK_LOG_REUTRN] = $content;
        if ($content !== "0") {
            $errMsg[SDK_LOG_LOCATION] = $url;
            $logLevel = $content > 3 ? 'warn' : 'error';
            self::$logLevel($errMsg, __CLASS__);
            if ($content) {
                $message = isset($errMsgCode[$content]) ? $errMsgCode[$content] : "UNDEFINED ERROR:\t{$content}";
                self::setErrNo($content);
            }
            return false;
        }
        self::log($errMsg, __CLASS__, true);
        return true;
    }
    /**
     * 开通CAS白名单
     * @param string $message
     * @param int $appId
     * @param string $domain
     * @param boolean $isSelf 是否开启自身防沉迷
     * @param string $env
     */
    public static function setCasDomain (&$message, $appId, $domain, $isSelf = false, $env = SDK_ENV_TEST)
    {
/*        if (!$domain) {
        	return true;
        }
        if (($casInfo = self::queryCasDomain($message, $domain, $env)) && $casInfo['appid']!=$appId) {
        	$message = " {$domain} has been registerd by app({$casInfo['appid']}) ";
        	self::setErrNo(SDOServiceErrorCode::API_EC_MATCH);
            return false;
        }
        if (!$appId) {
            $message = "Invalid Parameter";
            self::setErrNo(SDOServiceErrorCode::API_EC_PARAM);
        	return false;
        }
        $wsdl = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_CAS_WSDL) : sdk_fetch_config(
        SDK_ENV . self::CAS_WSDL);
        $params = array(
            'strAppID' => $appId, 
            'strDomainName' => $domain, 
            'iRetOid' => 0, 
            'iRetPt' => 0, 
            'iRetSDID' => 0, 
            'iRetSubApp' => 1, 
            'iEkeyType' => 0, 
            'iEkeyStatus' => 0, 
            'iIDCard' => 1, 
            'iValidate' => 1
        );
        if (! $isSelf) {
            $params['iIDCard'] = 0;
        }      
        
        $options = array(
            'soap_version' => SOAP_1_2
        );
        $result = self::soapRequest('Set', $params, $wsdl, $options, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $appId . "|{$domain}|".intval($isSelf) , SDK_LOG_ENV=>$env);
        if ($result === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $wsdl;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $errMsg[SDK_LOG_REUTRN] = json_encode($result);
        if (! $result->service->recordCount) {
            $errMsg[SDK_LOG_LOCATION] = $wsdl;
            self::warn($errMsg, __CLASS__);
            self::setErrNo(SDOServiceErrorCode::API_EC_COMMON_ERROR);
            return false;
        }
        self::log($errMsg, __CLASS__, true);*/
        if ($env!=SDK_ENV_TEST) {
            if (!self::insertTbtrustDomainName($message, $domain, 0, $env)) {
            	return false;
            }
        	self::writeCasDailyLog($appId, $domain);
        }
        return true;
    }    
    /**
     * 获取domain在cas中信息
     * @param string $message
     * @param string $domain
     * @param string $env
     * @return array|boolean   array("id"=> 主键, "appid"=>应用ID, "domain"=>域名，“purview"=>， "validate"=>是否生效)
     */
    public static function queryCasDomain(&$message, $domain, $env = SDK_ENV_TEST)
    {
        return self::queryTrustDomainName(&$message, $domain,  $env);
/*        $wsdl = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_CAS_WSDL) : sdk_fetch_config(
        SDK_ENV . self::CAS_WSDL);
        $params = array(
            'strDomainName' => $domain
        );
        $options = array(
            'soap_version' => SOAP_1_2
        );
        $result = self::soapRequest('Query', $params, $wsdl, $options, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $domain , SDK_LOG_ENV=>$env);
        if ($result === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $wsdl;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        if (! $result->service->recordCount) {
            return false;
        }
        
        return (array)$result->service->url;*/
    } 
    /**
     * 删除CAS域名
     * @param string $message
     * @param int $appId
     * @param string $domain
     * @param string $env
     * @return boolean
     */
    public static function removeCasDomain(&$message, $appId, $domain, $env = SDK_ENV_TEST)
    {
/*        if (!$domain) {
        	return true;
        }
        if (($casInfo = self::queryCasDomain($message, $domain, $env)) && $casInfo['appid']!=$appId) {
        	$message = " {$domain} not belong to this app ";
        	self::setErrNo(SDOServiceErrorCode::API_EC_MATCH);
            return false;
        }
        $wsdl = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_CAS_WSDL) : sdk_fetch_config(
        SDK_ENV . self::CAS_WSDL);
        $params = array(
            'strDomainName' => $domain
        );
        $options = array(
            'soap_version' => SOAP_1_2
        );
        
        $result = self::soapRequest('Remove', $params, $wsdl, $options, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $appId . "|" .$domain, SDK_LOG_ENV=>$env);
        if ($result === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $wsdl;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }        
        $errMsg[SDK_LOG_REUTRN] = json_encode($result);
        if ($result->RemoveResult !== 1) {
            self::warn($errMsg, __CLASS__);
            if ($result->RemoveResult === 0) {
            	return true;
            }
            self::setErrNo(SDOServiceErrorCode::API_EC_COMMON_ERROR);
            return false;
        }
        self::log($errMsg, __CLASS__, true);*/
    	if ($env!=SDK_ENV_TEST) {
            if (!self::deleteTbtrustDomainName($message, $domain, 0, $env)) {
            	return false;
            }
        }
        return true;
    }
    public static function syncCasServer(&$message, $domain, $env = SDK_ENV_TEST)
    {
        if (!$domain) {
        	return true;
        }
        $wsdl = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_CAS_WSDL) : sdk_fetch_config(
        SDK_ENV . self::CAS_WSDL);
        $params = array(
            'strCasServerIP' => $domain
        );
        $options = array(
            'soap_version' => SOAP_1_2
        );
        
        $result = self::soapRequest('Remove', $params, $wsdl, $options, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $domain, SDK_LOG_ENV=>$env);
        if ($result === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $wsdl;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }        
        $errMsg[SDK_LOG_REUTRN] = json_encode($result);
        if ($result->RemoveResult !== 1) {
            self::warn($errMsg, __CLASS__);
            if ($result->RemoveResult === 0) {
            	return true;
            }
            self::setErrNo(SDOServiceErrorCode::API_EC_COMMON_ERROR);
            return false;
        }
        self::log($errMsg, __CLASS__, true);
        return true;
    }
    
    public static function insertTbtrustDomainName(&$message, $domain, $clientUserId=0, $env = SDK_ENV_TEST)
    {
        if (!$domain || $env==SDK_ENV_TEST) {
        	return true;
        }
        $wsdl = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_SSO_WSDL) : sdk_fetch_config(
        SDK_ENV . self::SSO_WSDL);
        $params = array(
            'arg0'=>array(
                'domainName' => $domain,
                'clientUserId' => $clientUserId
            )
        );
        $options = array(
            'soap_version' => SOAP_1_1
        );        
        $result = self::soapRequest('insertTbtrustDomainName', $params, $wsdl, $options, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $domain."|".$clientUserId, SDK_LOG_ENV=>$env);
        if ($result === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $wsdl;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }      
        $errMsg[SDK_LOG_REUTRN] = json_encode($result);  
        if ($result->return->result !== '0') {
            $errMsg[SDK_LOG_LOCATION] = $wsdl;
            self::warn($errMsg, __CLASS__);
            $message = $result->return->resMsg;
            self::setErrNo($result->return->result);
            if ($result->return->result==-10363502) {
            	return true;
            }
            return false;
        }
        self::log($errMsg, __CLASS__, true);
        return true;
    }
    
	public static function deleteTbtrustDomainName(&$message, $domain, $clientUserId=0, $env = SDK_ENV_TEST)
    {
        if (!$domain || $env==SDK_ENV_TEST) {
        	return true;
        }
        $wsdl = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_SSO_WSDL) : sdk_fetch_config(
        SDK_ENV . self::SSO_WSDL);
        $params = array(
            'arg0'=>array(
                'domainName' => $domain,
                'clientUserId' => $clientUserId
            )
        );
        $options = array(
            'soap_version' => SOAP_1_1
        );        
        $result = self::soapRequest('deleteTbtrustDomainName', $params, $wsdl, $options, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $domain."|".$clientUserId, SDK_LOG_ENV=>$env);
        if ($result === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $wsdl;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }      
        $errMsg[SDK_LOG_REUTRN] = json_encode($result);  
        if ($result->return->result !== '0') {
            $errMsg[SDK_LOG_LOCATION] = $wsdl;
            self::warn($errMsg, __CLASS__);
            $message = $result->return->resMsg;
            self::setErrNo($result->return->result);
            if ($result->return->result==-10363507) {
            	return true;
            }
            return false;
        }
        self::log($errMsg, __CLASS__, true);
        return true;
    }
    
    public static function queryTrustDomainName(&$message, $domain,  $env = SDK_ENV_TEST)
    {
        if (!$domain || $env==SDK_ENV_TEST) {
        	return false;
        }
        $wsdl = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_SSO_WSDL) : sdk_fetch_config(
        SDK_ENV . self::SSO_WSDL);
        $params = array(
            'arg0'=>array(
                'domainName' => $domain
            )
        );
        $options = array(
            'soap_version' => SOAP_1_1,
            'trace' => 1
        );        
        
        $result = self::soapRequest('queryTrustDomainName', $params, $wsdl, $options, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $domain, SDK_LOG_ENV=>$env);
        if ($result === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $wsdl;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }  
           
        $errMsg[SDK_LOG_REUTRN] = json_encode($result);  
        if ($result->return->result !== '0') {
            $errMsg[SDK_LOG_LOCATION] = $wsdl;
            self::warn($errMsg, __CLASS__);
            $message = $result->return->resMsg;
            self::setErrNo($result->return->result);
            return false;
        }
        self::log($errMsg, __CLASS__, true);
        if (!isset($result->return->trustDomainNameVOList) || !$result->return->trustDomainNameVOList) {
        	return false;
        }
        return (array)$result->return->trustDomainNameVOList;
    }
    
    public static function validTrustIP($ip)
    {
        $ip = trim($ip);
        if ($ip=='61.172.252.173') {
        	//return false;
        }
       
        $fbList = array(
          -565625600 => -565625576,//'222.73.61.0'=>'222.73.61.24',
          -565625344 => -565625320,//'222.73.62.0'=>'222.73.62.24',
          -565625088 => -565625064,//'222.73.63.0'=>'222.73.63.24',
          -565638144 => -565638120,//'222.73.12.0'=>'222.73.12.24',
          -768402176 => -768402152,//'210.51.29.0'=>'210.51.29.24',
          2099717376 => 2099717400,//'125.39.37.0'=>'125.39.37.24',
          2099734784 => 2099734808,//'125.39.105.0'=>'125.39.105.24'
        );
        $ipLong = ip2long($ip);
        foreach($fbList as $start=>$end) {
            if ($ip>=$start && $ip<=$end) {
            	return false;
            }
        }
        return true;
    }
    protected static function mail($ip, $appId, $areaId, $groupId)
    {
        $phpmailerlite = new PHPMailer();
        try {
    	  $phpmailerlite->CharSet = "UTF-8";
    	  $phpmailerlite->IsSMTP();
    	  $phpmailerlite->SMTPAuth = false;
    	  $phpmailerlite->Host = '121.14.48.194';
    	  $phpmailerlite->SetFrom("openadmin@snda.com", "openIII", false);
    	  $phpmailerlite->AddReplyTo("no-reply@snda.com", "no-reply");
    	  $mailList = sdk_fetch_config(SDK_ENV . self::TRUST_IP_MAILER);
    	  foreach($mailList as $mail) {
    	      $phpmailerlite->AddAddress($mail);
    	  }    	  
    	  $phpmailerlite->Subject = "需要返回PT的游戏新增登录服务器，请运维同事添加至Linux VS列表";
    	  $content = file_get_contents(dirname(__FILE__) . '/libraries/email.html');
    	  $content = strtr($content, array('{appId}'=>$appId, '{areaId}'=>$areaId, '{groupId}'=>$groupId, '{ip}'=>$ip));
    	  $phpmailerlite->MsgHTML($content);
    	  $phpmailerlite->Send();
    	  $mailFlag = TRUE;
    	}
    	catch (phpmailerException $e) {
    	  echo $e->getMessage();
    	  $mailFlag = FALSE;
    	} catch (Exception $e) {
    	   echo $e->getMessage();
    	  $mailFlag = FALSE;
    	}
    	return $mailFlag;
    }
    
    private static function writeCasDailyLog($appId, $domain)
    {
        $file = "/uploads/open/log/sdk/cas_".date("Ymd").".log";
        $fp = fopen($file, "ab+");
        fwrite($fp, "{$appId},{$domain}\n");
        fclose($fp);
    }
     
    /**
     * 自检函数
     */
    public static function selfTest ()
    {
        $arr = array(
            sdk_fetch_config(SDK_ENV . self::AUTHEN_APP_OP_URL), 
            sdk_fetch_config(SDK_ENV . self::PRE_AUTHEN_APP_OP_URL), 
            sdk_fetch_config(SDK_ENV . self::AUTHEN_APP_SEARCH_URL), 
            sdk_fetch_config(SDK_ENV . self::MODIFY_PERM_USER)
        );
        return self::curlTest($arr);
    }
}
